package cn.micro.request.log.filters;

import cn.micro.core.context.CurrentContext;
import cn.micro.core.util.StringUtil;
import cn.micro.core.util.TraceIdUtil;
import org.slf4j.MDC;
import org.springframework.core.Ordered;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.atomic.AtomicInteger;

import static cn.micro.core.constant.Cants.CURRENT_TRACE_ID;
import static cn.micro.core.constant.Cants.X_CURRENT_REQUEST_ID;

/**
 * request id 设置进 MDC
 */
public class MDCRequestFilter extends OncePerRequestFilter implements Ordered {
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String traceId = request.getHeader(X_CURRENT_REQUEST_ID);
        try {
            if (StringUtil.isEmpty(traceId)) {
                traceId = TraceIdUtil.genTraceId();
            }
            MDC.put(X_CURRENT_REQUEST_ID, "[" + traceId + "]");
            CurrentContext.set(CURRENT_TRACE_ID, traceId);
            CurrentContext.set(traceId, new AtomicInteger(0));
            filterChain.doFilter(request, response);
        } finally {
            MDC.remove(X_CURRENT_REQUEST_ID);
            CurrentContext.removeKey(traceId);
            CurrentContext.removeKey(CURRENT_TRACE_ID);
        }
    }

    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE;
    }

    @Override
    public void destroy() {
        MDC.clear();
    }
}
